import access from '@ohos.bluetooth.access';
import ble from '@ohos.bluetooth.ble';
import { log } from '../util';

import type { BluetoothState, StateChangeHandler, ScanFilter, ScanOptions, BLEDeviceFindHandler } from './type'

const TAG = 'discover_system'

export function enableBluetooth(): boolean {
  try {
    access.enableBluetooth();
    log.info(TAG, 'enableBluetooth success')
    return true
  } catch (err) {
    log.error(TAG, 'enableBluetooth fail', JSON.stringify(err) ?? '')
    return false
  }
}

export function disableBluetooth(): boolean {
  try {
    access.disableBluetooth();
    log.info(TAG, 'disableBluetooth success')
    return true
  } catch (err) {
    log.error(TAG, 'disableBluetooth fail', JSON.stringify(err) ?? '')
    return false
  }
}

export function getState(): BluetoothState {
  try {
    const state = access.getState();
    log.info(TAG, 'getState success', state.toString())
    return state
  } catch (err) {
    log.error(TAG, 'getState fail', JSON.stringify(err) ?? '')
    return -1
  }
}

export function onStateChange(handler:StateChangeHandler): boolean {
  try {
    access.on('stateChange', handler)
    log.info(TAG, 'onStateChange success')
    return true
  } catch (err) {
    log.error(TAG, 'onStateChange fail', JSON.stringify(err) ?? '')
    return false
  }
}

export function offStateChange(handler?:StateChangeHandler): boolean {
  try {
    access.off('stateChange', handler)
    log.info(TAG, 'offStateChange success')
    return true
  } catch (err) {
    log.error(TAG, 'offStateChange fail', JSON.stringify(err) ?? '')
    return false
  }
}

export function startBLEScan(filters: Array<ScanFilter> = null, options?: ScanOptions): boolean {
  try {
    ble.startBLEScan(filters, options)
    log.info(TAG, 'startBLEScan success')
    return true
  } catch (err) {
    log.error(TAG, 'startBLEScan fail', JSON.stringify(err) ?? '')
    return false
  }
}

export function stopBLEScan(): boolean {
  try {
    log.info(TAG, 'stopBLEScan start')
    ble.stopBLEScan()
    log.info(TAG, 'stopBLEScan success')
    return true
  } catch (err) {
    log.error(TAG, 'stopBLEScan fail', JSON.stringify(err) ?? '')
    return false
  }
}

export function onBLEDeviceFind(handler: BLEDeviceFindHandler): boolean {
  try {
    ble.on('BLEDeviceFind', handler)
    log.info(TAG, 'onBLEDeviceFind success')
    return true
  } catch (err) {
    log.error(TAG, 'onBLEDeviceFind fail', JSON.stringify(err) ?? '')
    return false
  }
}

export function offBLEDeviceFind(handler: BLEDeviceFindHandler): boolean {
  try {
    ble.off('BLEDeviceFind', handler)
    log.info(TAG, 'offBLEDeviceFind success')
    return true
  } catch (err) {
    log.error(TAG, 'offBLEDeviceFind fail', JSON.stringify(err) ?? '')
    return false
  }
}